const {
	ERROR
} = require('../../common/error')
// const {
//   getNeedCaptcha,
//   verifyCaptcha
// } = require('../../lib/utils/captcha')
// const {
//   verifyEmailCode
// } = require('../../lib/utils/verify-code')
const {
	userCollection,
	EMAIL_SCENE,
	CAPTCHA_SCENE,
	LOG_TYPE
} = require('../../common/constants')
const {
	findUser
} = require('../../lib/utils/account')
// const PasswordUtils = require('../../lib/utils/password')
// 判断账号是否注册
async function wjfSearchUser(params = {}) {
	const schema = {
		username: {
			required: false,
			type: 'username'
		},
		// mobile: {
		// 	required: false,
		// 	type: 'mobile'
		// },
		email: {
			required: false,
			type: 'email'
		}
	}
	this.middleware.validate(params, schema)
	const {
		username,
		email
	} = params;
	var userMatched;
	if (params.hasOwnProperty('username')) {
		// 根据用户名查找匹配的用户
		userMatched = await findUser.call(this, {
			userQuery: {
				username
			},
			authorizedApp: [this.getClientInfo().appId]
		})
	} else if (params.hasOwnProperty('email')) {
		// 根据邮箱查找匹配的用户
		userMatched = await findUser.call(this, {
			userQuery: {
				email
			},
			authorizedApp: [this.getClientInfo().appId]
		})

	}
	if (userMatched.length === 0) {
		throw {
			errCode: ERROR.ACCOUNT_NOT_EXISTS
		}
	} else if (userMatched.length > 1) {
		throw {
			errCode: ERROR.ACCOUNT_CONFLICT
		}
	}
	return {
		errCode: 0,
		email:userMatched[0].email
	}
}
/**
 * 判断用户是否存在
 */
async function wjfSearchUserExists(params = {}) {
	const schema = {
		username: {
			required: false,
			type: 'username'
		},
		// mobile: {
		// 	required: false,
		// 	type: 'mobile'
		// },
		email: {
			required: false,
			type: 'email'
		}
	}
	this.middleware.validate(params, schema)
	const {
		username,
		email
	} = params;
	var userMatched;
	if (params.hasOwnProperty('username')) {
		// 根据用户名查找匹配的用户
		userMatched = await findUser.call(this, {
			userQuery: {
				username
			},
			authorizedApp: [this.getClientInfo().appId]
		})
	} else if (params.hasOwnProperty('email')) {
		// 根据邮箱查找匹配的用户
		userMatched = await findUser.call(this, {
			userQuery: {
				email
			},
			authorizedApp: [this.getClientInfo().appId]
		})

	}
	// if (userMatched.length === 0) {
	// 	throw {
	// 		errCode: ERROR.ACCOUNT_NOT_EXISTS
	// 	}
	// } else if (userMatched.length > 1) {
	// 	throw {
	// 		errCode: ERROR.ACCOUNT_CONFLICT
	// 	}
	// }
	return {
		errCode: 0,
		resUserMatched:userMatched
	}
}
module.exports = {
	wjfSearchUser,
	wjfSearchUserExists
}
